<?php

namespace App\Console\Commands;

use App\Models\Report;
use Illuminate\Console\Command;
use Carbon\Carbon;


class ChargeCountMonthFix extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'charge:month-report-fix';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '流量统计月报表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {    
        $year  = intval(date('Y'));     // this year
        $month = intval(date('n')) - 1;     // this month
        $this->_mkdata($month, $year);


    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function _mkdata($month = 0, $year = 0)
    {
        $dayStart = ($month == 1) ? 1 : 0;
        $dayEnd   = ($month == 12 || $month == 0) ? 1 : 0; //按天计

        $timeStart = mktime(0, 0, 0, $month, $dayStart, $year);
        $timeEnd   = mktime(0, 0, 0, $month+1, $dayEnd, $year);

        $dateStart = date('Y-m-d', $timeStart);
        $dateEnd   = date('Y-m-d', $timeEnd);

        $fullMonth = date('Y-m', $timeEnd);


        $this->info(sprintf('month:     %s', $fullMonth));
        $this->info(sprintf('dateStart: %s', $dateStart));
        $this->info(sprintf('dateEnd:   %s', $dateEnd));


        $res = Report::where("report_date", ">=", $dateStart)
                        ->where("report_date", "<=", $dateEnd)
                        ->where('type','charge_count_day_report')->get();

        $values = $res->map(function ($item){
            return $item->value;
        });

        //进行月累加
        $newArr=[];
        $row=$values->first();
        foreach ($row as $k=>$v){
            $newArr[$k]=$values->sum($k);
        }


        $this->info($fullMonth);

        //存入数据库
        $report_type = 'charge_count_month_report';
        $report = Report::where('type', $report_type)
                            ->where('report_date', $fullMonth)
                            ->first();
        if (!$report) {
            $report = new Report;
            $report->report_date = $fullMonth;
            $report->type = $report_type;
        }

        $report->value = $newArr;
        $report->save();

        $this->info('月收入统计成功');
    }
}
